<script setup>
import {
    Edit,
    Delete,
    Share
} from '@element-plus/icons-vue'
import { addProject, getProjectList, deleteProjectByid, updateProjectById,updateStatusById } from '@/api/admin.js'
import { ref, onMounted } from 'vue'
import { ElDialog, ElMessage, ElMessageBox,ElForm, ElFormItem, ElSelect, ElOption, ElButton  } from 'element-plus'

// 定义图片地址数组
import png1 from '@/assets/match/jpg_1.jpg'
import png2 from '@/assets/match/jpg_2.jpg'
import png3 from '@/assets/match/jpg_3.jpg'
import png4 from '@/assets/match/jpg_4.png'
import png5 from '@/assets/match/jpg_5.jpeg'
import png6 from '@/assets/match/jpg_6.jpeg'
import { Loading } from 'element-plus/es/components/loading/src/service'

// 定义响应式变量
const projectList = ref([])
const images = ref([png1, png2, png3, png4, png5, png6])
const visibleDrawer = ref(false)
const direction = ref('rtl')
const project = ref({
  name: '',
  introduction: '',
  type: '',
  gtype: '',
  upnum: '',
  place: '',
  renum: '',
  startTime: '',
  eventTime:'',
  endTime: '',
  id: null // 添加 id 用于识别项目
})
const isEditMode = ref(false) // 标志是否为编辑模式
const dateFormat = 'YYYY-MM-DD HH:mm:ss'

// 获取项目列表
const list = async () => {
  Loading.value = true
  try {
    const resp = await getProjectList()
    projectList.value = resp.data
  } catch (error) {
    ElMessage.error("获取数据失败。")
  } finally {
    Loading.value = false
  }
}

// 删除项目
const deleteProject = async (projectId) => {
  try {
    await ElMessageBox.confirm('是否删除该活动?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteProjectByid(projectId)
    list()
    ElMessage.success('删除成功')
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('删除已取消')
    } else {
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 打开对话框用于创建或编辑项目
const showDialog = (row) => {
  if (row) {
    isEditMode.value = true
    Object.assign(project.value, row) // 用项目数据填充表单
  } else {
    isEditMode.value = false
    resetProject() // 清空表单，用于创建新项目
  }
  visibleDrawer.value = true
}

//关闭对话框
const cancelClick = () => {
  visibleDrawer.value = false
  resetProject()
}

// 重置项目数据
const resetProject = () => {
  Object.assign(project.value, {
    name: '',
    introduction: '',
    type: '',
    gtype: '',
    upnum: '',
    place: '',
    renum: '',
    startTime: '',
    eventTime:'',
    endTime: '',
    id: null
  })
}

// 创建或更新项目
const confirmClick = async () => {
  try {
    if (isEditMode.value) {
      // 更新现有项目
      await updateProjectById(project.value.projectId, project.value)
      ElMessage.success("更新成功！")
    } else {
      // 创建新项目
      // resetProject()
      await addProject(project.value)
      ElMessage.success("创办成功！")
    }
    visibleDrawer.value = false
    resetProject()
    list()
  } catch (error) {
    ElMessage.error("操作失败，请重试")
  }
}

//更新状态
// 打开编辑框
const visibleDialog = ref(false);
const currentProject = ref({});

const openEditDialog = (row) => {
  visibleDialog.value = true;
  currentProject.value = { ...row }; // 克隆项目数据
  console.log(currentProject.value)
};

//提交状态
const updateStatus = async () => {
  const { status,projectId } = currentProject.value
  try {
    await updateStatusById(projectId,{status})
    ElMessage.success('状态修改成功')
    visibleDialog.value=false;
    list()
  } catch (error){
    ElMessage.error('状态修改失败')
    visibleDialog.value=false;
  }
}

// 组件挂载时自动获取数据
onMounted(() => {
  list()
});

</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>赛事页面</span>
              <div class="extra">
                <el-button type="primary" @click="visibleDrawer = true;">创办比赛</el-button>
              </div>
            </div>
        </template>

        <!-- main -->
        <div class="main">
            <!-- 轮播图 -->
            <el-carousel :interval="4000" type="card" height="200px">
                <el-carousel-item v-for="(imgSrc, index) in images" :key="index">
                    <img class="image" :src="imgSrc" alt="轮播图" />
                </el-carousel-item>
            </el-carousel>

        </div>

        <!-- 项目列表 -->
        <div class="big" style="width: 100%; text-align: center;">
          <el-table :data="projectList" style="width: 100%">
            <el-table-column label="项目名称" width="150" prop="name"></el-table-column>
            <el-table-column prop="type" label="比赛类型" width="80" :formatter="(row) => (row.type === '0' ? '个人' : '团体')"></el-table-column>
            <el-table-column prop="gtype" label="男子/女子" width="110" :formatter="(row) => (row.gtype === '1' ? '男子' : '女子')"></el-table-column>
            <el-table-column label="比赛地点" width="120" prop="place"></el-table-column>
            <el-table-column label="开始时间" width="200" prop="startTime"></el-table-column>
            <el-table-column label="结束时间" width="200" prop="endTime"></el-table-column>
            <el-table-column label="状态" prop="status">
              <template #default="{ row }">
                <span
                  :class="{
                    'status-active': row.status === 2,
                    'status-inactive': row.status === 1,
                    'status-reject': row.status === 0
                  }">
                  {{ row.status === 2 ? '已结束' : row.status === 1 ? '进行中' : '未开始' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
              <template #default="{ row }">
                <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                <el-button :icon="Delete" circle plain type="danger" @click="deleteProject(row.projectId); successMsg()"></el-button>
                <el-button size="mini" type="primary" @click="openEditDialog(row)">修改状态</el-button>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty description="没有数据" />
            </template>
          </el-table>
        </div>

      <!-- 抽屉 -->
      <el-drawer v-model="visibleDrawer" :direction="direction" size="50%">
      <!-- Drawer Header -->
      <template #header>
        <h4>赛事信息</h4>
      </template>
    
      <!-- Drawer Content -->
      <template #default>
        <el-form label-width="100px">
          <!-- 赛事名称 -->
          <el-form-item label="赛事名称">
            <el-input v-model="project.name" placeholder="请输入赛事名称" />
          </el-form-item>
        
          <!-- 比赛人数 -->
          <el-form-item label="比赛人数">
            <el-input v-model="project.upnum" placeholder="请输入比赛人数" />
          </el-form-item>
        
          <!-- 比赛地点 -->
          <el-form-item label="比赛地点">
            <el-input v-model="project.place" placeholder="请输入比赛地点" />
          </el-form-item>
        
          <!-- 裁判员数量 -->
          <el-form-item label="裁判员数量">
            <el-input v-model="project.renum" placeholder="请输入裁判员数量" />
          </el-form-item>
        
          <!-- 男子/女子 -->
          <el-form-item label="男子/女子">
            <el-select v-model="project.gtype" placeholder="请选择" size="default" style="width: 240px">
              <el-option label="男子" value="1" />
              <el-option label="女子" value="0" />
            </el-select>
          </el-form-item>
        
          <!-- 比赛类型 -->
          <el-form-item label="比赛类型">
            <el-radio-group v-model="project.type">
              <el-radio label="0">个人</el-radio>
              <el-radio label="1">团体</el-radio>
            </el-radio-group>
          </el-form-item>
        
          <!-- 开始时间 -->
        <el-form-item label="报名开始时间">
          <el-date-picker
            v-model="project.startTime"
            type="datetime"
            placeholder="选择开始时间"
            :format="dateFormat"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <!-- 结束时间 -->
        <el-form-item label="报名结束时间">
          <el-date-picker
            v-model="project.endTime"
            type="datetime"
            placeholder="选择结束时间"
            :format="dateFormat"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <!-- 比赛时间 -->
        <el-form-item label="比赛时间">
          <el-date-picker
            v-model="project.eventTime"
            type="datetime"
            placeholder="选择比赛时间"
            :format="dateFormat"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
          <!-- 规则介绍 -->
          <el-form-item label="规则介绍">
            <el-input
              v-model="project.introduction"
              type="textarea"
              placeholder="请输入规则介绍"
              :autosize="{ minRows: 2, maxRows: 4 }"
            />
          </el-form-item>
        </el-form>
      </template>
    
      <!-- Drawer Footer -->
      <template #footer>
        <div style="text-align: right">
          <el-button @click="cancelClick">关闭</el-button>
          <el-button type="primary" @click="confirmClick">确定</el-button>
        </div>
      </template>
      </el-drawer>

      <!-- 编辑状态弹出框 -->
      <el-dialog title="更改状态" v-model="visibleDialog" width="30%">
        <el-form label-width="100px">
          <el-form-item label="状态">
            <el-select v-model="currentProject.status" placeholder="请选择状态">
              <el-option label="未开始" :value="0"></el-option>
              <el-option label="进行中" :value="1"></el-option>
              <el-option label="已结束" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="visibleDialog = false">取消</el-button>
          <el-button type="primary" @click="updateStatus">确定</el-button>
        </template>
      </el-dialog>

    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .editor {
        width: 100%;

        :deep(.ql-editor) {
            min-height: 200px;
        }
    }

    /* 轮播图 */
    .el-carousel__item h3 {
        color: #475669;
        opacity: 0.75;
        line-height: 200px;
        margin: 0;
        text-align: center;
    }

    .image {
        width: 100%;
        /* 宽度填充容器 */
        height: 100%;
        /* 高度填充容器 */
        object-fit: cover;
        /* 图片覆盖容器，保持宽高比 */
    }

    .el-carousel__item:nth-child(2n) {
        background-color: #99a9bf;
    }

    .el-carousel__item:nth-child(2n + 1) {
        background-color: #d3dce6;
    }


    /* 内容显示 */
    .big {
        display: flex;
        justify-content: space-between;
    }
}


/*时间选择样式*/
.block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.status-active {
  color: green;
}
.status-inactive {
  color: orange;
}
.status-reject {
  color: red;
}
</style>